/**
 * 将所有Sprite 类型的 尺寸检测一遍，
 * 如果高或宽大于1024的，并且尺寸不是2的幂次，则使用 toNearest 调整尺寸
 * 如果高和宽均小于1024， 并且尺寸不是4的倍数，则直接resize 成4的倍数
 */

 const fs = require('fs');
 const path = require('path');
 const getInfo = require('image-size')
 var child_process = require('child_process');
 
 var current = process.cwd(); // 当前路径
 
 var isWindows = path.sep === '\\'
 
 const resPath = current.split('image-tool')[0] + 'sesame-unity/sesame/Assets/Game/Res/Res';
 const dynamicPath = path.join(resPath, 'Dynamic');
 const cdnPath = path.join(resPath, 'CDN');
 
function isFile(path) {
  return x.indexOf('.') !== -1
}

function isMeta(path) {
  return x.indexOf('.meta') >= 0
}

function isImage(path) {
  return isFile(path) && (path.indexOf('.png') > 0 || path.indexOf('.jpg') > 0 || path.indexOf('.jpeg') > 0)
}


function GetPathes(parentPath, filePathes, format) {
  format = format ?? '.png'// 默认处理透明图片
  const pathes = fs.readdirSync(parentPath);
  pathes.forEach((fileName) => {
    let isFile = fileName.indexOf('.') >= 0;
    const fullPath = path.join(parentPath, fileName)
    if (fileName.indexOf('VERSION') >= 0) return;
    if (fileName.indexOf('sheet') >= 0) return;
    if (fileName.indexOf('placeholder') >= 0) return;
    if (fullPath.indexOf('num' + path.sep) >= 0) return;
    if (isFile) {
      if (fileName.toLowerCase().endsWith(format)) { 
        filePathes.push(fullPath);
      }
    } else {
      GetPathes(path.join(fullPath), filePathes, format);
    }
  });
}

// textureType: 0    Default
// textureType: 8    Sprite

// TOSmaller : 3
// TOLarge: 2
// TONearest: 1
// None: 0
function main() {
  var filePathes = [];
  GetPathes(resPath, filePathes, '.jpg.meta');
  filePathes.forEach((x) => {
    const content = fs.readFileSync(x);
    var isContentChange = false;
    if (content.indexOf("textureType: 0") > 0) { // Texture
      if (content.indexOf('nPOTScale: 0')) {
        isContentChange = true;
        content.replace('nPOTScale: 0', "nPOTScale: 1");
      }
    } else if (content.indexOf("textureType: 8") > 0) { // Sprite
      var info = getInfo(x);
      if (info.width > 1024 || info.height > 1024) {
        
      } else {
        if (info.width % 4 != 0 || info.height % 4 != 0) {
          // 不是四的倍数
          
        }
      }
    }
    
    if (content.indexOf('enableMipMap: 1')) {
      content.replace("enableMipMap: 1", "enableMipMap: 0");
      isContentChange = true;
    }

    if (isContentChange) {
      fs.writeFileSync(x, content);
    }
  })
}

main();

 